﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace WindowsService1
{
    internal class SocketListener
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SocketListener));

        private readonly IPAddress ipAddress = IPAddress.Any;
        private readonly int port = 8081;

        public TcpListener TcpListener { get; private set; }
        public SocketListener() {
            this.TcpListener=new TcpListener(ipAddress,port);
            this.TcpListener.Start();
            log.Info("开始监听" + port + "端口");
            Console.WriteLine("开始监听" + port + "端口");

            while (true)
            {
                TcpClient tcpClient=this.TcpListener.AcceptTcpClient();

                log.Info("获取到了一个新连接");
                Console.WriteLine("获取到了一个新连接");

                Thread thread = new Thread(() => { 
                    handelClient(tcpClient);
                }) { IsBackground = true };
                thread.Start();

                Thread.Sleep(100);
            }
        }

        public void handelClient(TcpClient tcpClient)
        {
            if (!tcpClient.Connected) {
                log.Error("socket连接断开");
                Console.WriteLine("socket连接断开");

                tcpClient.Close();
                return;
            }

            byte[] buff=new byte[1024];
            NetworkStream stream= tcpClient.GetStream();

            while (true)
            {
                int bytesRead = stream.Read(buff, 0, buff.Length);
                if (bytesRead < 1) {
                    break;
                }
                string receivedData = Encoding.ASCII.GetString(buff, 0, bytesRead);
                log.Info("接收到消息：" + receivedData);
                Console.WriteLine("接收到消息：" + receivedData);

                Thread.Sleep(100);
            }

            stream.Close();
            tcpClient.Close();

        } 

    }
}
